package com.chixing.controller;

import com.chixing.service.CustomerService;
import com.chixing.util.MsgUtil;
import com.chixing.util.RandomUtil;
import com.chixing.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Controller
public class CustomerServlet {
    @Autowired
    private CustomerService customerService;

    // 保存短信用
    private Map<String, String> storage = new ConcurrentHashMap<>();


    //获得手机验证码 (1) 验证手机号是否已经注册过 + （2）获得验证码
    @RequestMapping("member/getcode")
    @ResponseBody
    public ServerResponse getcode(Long telno, HttpSession session) {
        System.out.println("getcode telno:" + telno);
        // 1. 登录业务中，查询手机号是否有效
        ServerResponse serverResponse = customerService.getByTelno(telno);

        if (serverResponse.getCode() == 200) {
            //若存在，再第三方平台 调用获得验证码接口
            String code = "123456";  //GetMessageCode.getCode(String.valueOf(telno));
            session.setAttribute("smsCode", code);
            System.out.println("用户已经注册,获得验证码成功");
            //返回验证码 ajax
            return ServerResponse.getDataSuccess(code);
        } else {  // 用户不存在
            return serverResponse;
        }

    }



    /**
     * 获取短信验证码
     * @return
     */
    private Map<String, String> doGetMsg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 返回参数
        Map<String, String> map = new HashMap<>();
        // 0 表示成功
        map.put("resCode", "0");
        // 1.获取手机号
        String mobilePhone = request.getParameter("mobilePhone");

        // 生产随机短信码
        String code = RandomUtil.createRandNum();
        System.out.println("------ 验证码：" + code);

        // 2.使用工具类获取短信
        int returnCode = MsgUtil.sendMsg(mobilePhone, code);

        // 3.判断短信发送结果
        if (returnCode != 0) {
            // 返回失败
            map.put("resCode", "1");
            return map;
        }

        // 将短信码保存起来，使用全局变量
        storage.put(mobilePhone, code);

        // 返回成功
        return map;
    }

}
